package com.techwells.learningkites.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Base64;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RatingBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.lidroid.xutils.BitmapUtils;
import com.techwells.learningkites.R;
import com.techwells.learningkites.adapter.CommentListAdapter;
import com.techwells.learningkites.adapter.SegmentGridAdapter;
import com.techwells.learningkites.adapter.ViewPagerAdapter;
import com.techwells.learningkites.model.MainPageViewModel;
import com.techwells.learningkites.model.RegisterViewModel;
import com.techwells.learningkites.model.VideoDetailViewModel;
import com.techwells.learningkites.networkaccess.KitesRequestUrl;
import com.techwells.learningkites.networkservice.Constant;
import com.techwells.learningkites.networkservice.KitesServiceMediator;
import com.techwells.learningkites.networkservice.model.Comment;
import com.techwells.learningkites.networkservice.model.Segment;
import com.techwells.learningkites.networkservice.model.Video;
import com.techwells.learningkites.networkservice.model.VideoAdditional;
import com.techwells.learningkites.networkservice.model.VideoDetail;
import com.techwells.taco.base.CommonBaseActivity;
import com.techwells.taco.mvvm.Route;
import com.techwells.taco.networkservice.ServiceMediator;
import com.techwells.taco.tasktool.TaskToken;
import com.techwells.taco.utils.ToastUtils;

public class VideoDetailActivity extends CommonBaseActivity implements OnItemClickListener, OnCheckedChangeListener, OnClickListener {
	
	private RadioGroup rgVideoDetail;
	private RadioButton rbSegment,rbComment;
	private ViewPager vpVideoDetail;
	private View viewSegment,viewComment;
	private List<View> views;
	private ViewPagerAdapter adapter;
	
	private ListView lvComment;
	private List<Map<String, Object>> listComment;
	private EditText comment;
	private TextView submit;
	private RatingBar rating;
	private ImageView more;
	private LinearLayout inputComment;
	
	private ImageView videoImg;
	private TextView introduce,word,segment,study;
	private GridView gridSegment;
	private List<Map<String, Object>> listSegm;
	private SimpleAdapter simpleAdapter,commentSimpleAdapter;
	
	private VideoDetailViewModel presentViewModel;
	private VideoDetail video;
	private VideoAdditional additional;
	private List<Comment> commentList;
	private Comment myComment;
	private BitmapUtils bitmapUtils;
	private SegmentGridAdapter segmentAdapter;
	private List<Segment> segmentList;
	private CommentListAdapter commentAdapter;
	private Button favorite;
	
	private boolean isRefresh = true;
	
	private EditText verify;
	private ImageView captcha;
	private String captchaString;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_video_detail);
		
		
//		initTitleBar(R.string.video, defaultLeftClickListener);
		initViews();
//		initViewPagerSegment();
		initViewPagerComment();
	}

	private void initViewPagerComment() {
		verify = (EditText) viewComment.findViewById(R.id.verify);
		captcha = (ImageView) viewComment.findViewById(R.id.captcha);
		lvComment = (ListView) viewComment.findViewById(R.id.lv_comment);
		
//		listComment = new ArrayList<Map<String, Object>>();
//		for (int i = 0; i < 12; i++) {
//			Map<String, Object> map = new HashMap<String, Object>();
//			map.put("user", "用户名");
//			listComment.add(map);
//		}
//		commentSimpleAdapter = new SimpleAdapter(this, listComment,
//				R.layout.item_commentlist, new String[]{"user"}, new int[]{R.id.user});
//		lvComment.setAdapter(commentSimpleAdapter);
		
		rating = (RatingBar) viewComment.findViewById(R.id.ratingbar);
		comment = (EditText) viewComment.findViewById(R.id.comment);
		submit = (TextView) viewComment.findViewById(R.id.submit);
		submit.setOnClickListener(this);
		
		more = (ImageView) viewComment.findViewById(R.id.more);
		more.setOnClickListener(this);
		
		inputComment = (LinearLayout) viewComment.findViewById(R.id.input_visibility);
	}

//	private void initViewPagerSegment() {
//		gridSegment = (GridView) viewSegment.findViewById(R.id.gv_segment);
//		
//		listSegm = new ArrayList<Map<String,Object>>();
//		for (int i = 0; i < 9; i++) {
//			HashMap<String, Object> map = new HashMap<String, Object>();  
//	        map.put("ItemImage", R.drawable.segment_demo);
//	        map.put("ItemText", "第一季第一集"); 
//	        listSegm.add(map);
//		}
//		simpleAdapter = new SimpleAdapter(this, listSegm, R.layout.item_segmentlist, 
//				new String[]{"ItemImage","ItemText"}, new int[]{R.id.item_image,R.id.item_text});
//		gridSegment.setAdapter(simpleAdapter);
//		gridSegment.setOnItemClickListener(this);
//	}

	private void initViews() {
		videoImg = (ImageView) findViewById(R.id.video_img);
		introduce = (TextView) findViewById(R.id.introduce);
		word = (TextView) findViewById(R.id.word);
		segment = (TextView) findViewById(R.id.segment);
		study = (TextView) findViewById(R.id.study);
		
		favorite = (Button) findViewById(R.id.favorite);
		favorite.setOnClickListener(this);
		
		rgVideoDetail = (RadioGroup) findViewById(R.id.rg_video_detail);
		rbSegment = (RadioButton) findViewById(R.id.tab_rb_segment);
		rbComment = (RadioButton) findViewById(R.id.tab_rb_comment);
		rgVideoDetail.setOnCheckedChangeListener(this);
		
		vpVideoDetail = (ViewPager) findViewById(R.id.vp_video_detail);
		viewSegment = getLayoutInflater().inflate(R.layout.viewpager_segment, null);
		viewComment = getLayoutInflater().inflate(R.layout.viewpager_comment, null);
		views = new ArrayList<View>();
		views.add(viewSegment);
		views.add(viewComment);
		adapter = new ViewPagerAdapter(this, views);
		vpVideoDetail.setAdapter(adapter);
		vpVideoDetail.setCurrentItem(0);
		vpVideoDetail.setOffscreenPageLimit(2);
		vpVideoDetail.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int position) {
				switch (position) {
				case 0:
					rbSegment.setChecked(true);
					break;
				case 1:
					rbComment.setChecked(true);
					break;
				default:
					break;
				}
				
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//		Route.route().nextController(VideoDetailActivity.this, SegmentDetailActivity.class.getName(), Route.WITHOUT_RESULTCODE);
		Intent intent = new Intent(this, SegmentDetailActivity.class);
		intent.putExtra("segmentId", segmentList.get(arg2).id);
		Route.route().nextControllerWithIntent(VideoDetailActivity.this, SegmentDetailActivity.class.getName(), Route.WITHOUT_RESULTCODE, intent);
	}


	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		switch (checkedId) {
		case R.id.tab_rb_segment:
			vpVideoDetail.setCurrentItem(0);
			break;
		case R.id.tab_rb_comment:
			vpVideoDetail.setCurrentItem(1);
			break;
		default:
			break;
		}
		
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.more:
			if (inputComment.getVisibility() == View.VISIBLE) {
				inputComment.setVisibility(View.GONE);
			}else {
				inputComment.setVisibility(View.VISIBLE);
				doRequestCaptcha();
			}
			
			break;
		case R.id.submit:
			if (comment.getText().toString().isEmpty()) {
				ToastUtils.show(this, "请输入评论");
			}else {
				doRequestAddComment();
			}
		case R.id.favorite:
			doRequestFavoriteVideo();
			
			break;

		default:
			break;
		}
		
	}
	

	@Override
	public void alreadyBindBaseViewModel() {
		// TODO Auto-generated method stub
		super.alreadyBindBaseViewModel();
		
		presentViewModel = (VideoDetailViewModel) baseViewModel;
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		if (isRefresh) {
			
			doRequestVideoDetail();
//			doRequestVideoAddtional();
			doRequestVideoComment();
			isRefresh = false;
		}
			

	}
	
	
	private void doRequestFavoriteVideo() {
		if (video != null) {
			HashMap<String, Object> argMap = new HashMap<String, Object>();	
			argMap.put("videoId", video.id);
			doTask(KitesServiceMediator.SERVICE_DO_FAVORITE_VIDEO,argMap);
		}
	}
	
	private void doRequestCaptcha() {
		doTask(KitesServiceMediator.SERVICE_GET_CAPTCHA,null);
	}

	private void doRequestVideoComment() {
		int videoId = getIntent().getIntExtra("videoId", 0);
		HashMap<String, Object> argMap = new HashMap<String, Object>();	
		argMap.put("videoId", videoId);
		doTask(KitesServiceMediator.SERVICE_GET_VIDEO_COMMENTS,argMap);
		
	}

	private void doRequestVideoAddtional() {
		int videoId = getIntent().getIntExtra("videoId", 0);
		HashMap<String, Object> argMap = new HashMap<String, Object>();	
		argMap.put("videoId", videoId);
		doTask(KitesServiceMediator.SERVICE_GET_VIDEO_ADDITIONAL,argMap);
		
	}

	private void doRequestVideoDetail() {
		int videoId = getIntent().getIntExtra("videoId", 0);
		HashMap<String, Object> argMap = new HashMap<String, Object>();	
		argMap.put("videoId", videoId);
		doTask(KitesServiceMediator.SERVICE_GET_VIDEO_DETAILS,argMap);
		
	}
	
	private void doRequestAddComment() {
		int videoId = getIntent().getIntExtra("videoId", 0);
		HashMap<String, Object> argMap = new HashMap<String, Object>();	
		argMap.put("videoId", videoId);
		argMap.put("comment", comment.getText().toString());
		argMap.put("rating", (int)rating.getRating());
		argMap.put("verifyType", Constant.verifyType);
		argMap.put("challenge", verify.getText().toString());
		doTask(KitesServiceMediator.SERVICE_ADD_VIDEO_COMMENT,argMap);
		
	}
	
	private void doRequestVideoSegments() {
		HashMap<String, Object> argMap = new HashMap<String, Object>();	
		argMap.put("serialId", video.serials.get(0).id);
		doTask(KitesServiceMediator.SERVICE_GET_VIDEO_SEGMENT,argMap);
		
	}
	
	@Override
	public void refreshData(TaskToken token) {
		// TODO Auto-generated method stub
		super.refreshData(token);
		
		String method = token.method;
		if (method.equals(KitesServiceMediator.SERVICE_GET_VIDEO_DETAILS)) {
			video = ((VideoDetailViewModel) baseViewModel).video;
			initTitleBar(video.cnName, defaultLeftClickListener);
			bitmapUtils = new BitmapUtils(this);
			bitmapUtils.display(videoImg, KitesRequestUrl.BASE_URL_IMG + video.poster);
			if (video.introduction.length() > 120) {
				introduce.setText(video.introduction.substring(0, 120) + "...");
			}else {
				introduce.setText(video.introduction);
			}
			
			
			word.setText(video.wordNum + "个词汇");
			segment.setText(video.chapterNum + "个视频");
			study.setText(video.learnedNum + "人已学习");
			
			if (video.serials.size() > 0) {
				doRequestVideoSegments();
			}
			
		}else if (method.equals(KitesServiceMediator.SERVICE_GET_VIDEO_SEGMENT)) {
			segmentList = ((VideoDetailViewModel) baseViewModel).segmentList;
			
			gridSegment = (GridView) viewSegment.findViewById(R.id.gv_segment);
			segmentAdapter = new SegmentGridAdapter(this, segmentList);
			gridSegment.setAdapter(segmentAdapter);
			gridSegment.setOnItemClickListener(this);
			
		}else if (method.equals(KitesServiceMediator.SERVICE_GET_VIDEO_ADDITIONAL)) {
			additional = ((VideoDetailViewModel) baseViewModel).additional;
			
		}else if (method.equals(KitesServiceMediator.SERVICE_GET_VIDEO_COMMENTS)) {
			commentList = ((VideoDetailViewModel) baseViewModel).commentList;
			commentAdapter = new CommentListAdapter(this, commentList);
			lvComment.setAdapter(commentAdapter);
			
		}else if (method.equals(KitesServiceMediator.SERVICE_ADD_VIDEO_COMMENT)) {
			myComment = ((VideoDetailViewModel) baseViewModel).comment;
//			commentList.add(myComment);
//			commentAdapter.notifyDataSetChanged();
			doRequestVideoComment();
			comment.setText("");
			verify.setText("");
			rating.setRating(0);
			if (inputComment.getVisibility() == View.VISIBLE) {
				inputComment.setVisibility(View.GONE);
			}else {
				inputComment.setVisibility(View.VISIBLE);
				doRequestCaptcha();
			}
			ToastUtils.show(this, "发表评论成功");
			
		}else if (method.equals(KitesServiceMediator.SERVICE_GET_CAPTCHA)) {
			captchaString = ((VideoDetailViewModel)baseViewModel).captcha;
			byte[] decodeByte = Base64.decode(captchaString, 0);
			Bitmap bitmap = BitmapFactory.decodeByteArray(decodeByte, 0, decodeByte.length);
			captcha.setImageBitmap(bitmap);
		}else if (method.equals(KitesServiceMediator.SERVICE_DO_FAVORITE_VIDEO)) {
			int returnCode = ((VideoDetailViewModel)baseViewModel).returnCode;
			if (returnCode == ServiceMediator.Service_Return_Success) {
				ToastUtils.show(this, "收藏成功");
			}
			
		}
	}

	@Override
	public void requestFailedHandle(TaskToken token, int errorCode,
			String errorMsg) {
		String method = token.method;
		if (method.equals(KitesServiceMediator.SERVICE_ADD_VIDEO_COMMENT)) {
			switch (errorCode) {
			case 461:
				ToastUtils.show(this, "验证码错误");
				break;
			case 460:
				ToastUtils.show(this, "验证码失效");
				break;
			case 400:
				ToastUtils.show(this, "请输入验证码");
				break;

			default:
				ToastUtils.show(this, errorMsg);
				break;
			}
		}
		
		
	}
	
	
}
